<template>
  <div class="pad-20" v-loading="loading" element-loading-text="加载中">
    <el-form label-position="right" label-width="120px">
      <el-form-item label="导入文件">
        <div v-if="uploadForm.fileName">{{ uploadForm.fileName }}</div>
        <el-upload
          class="upload-demo"
          ref="importOrder"
          name="files"
          action="/api/common/uploadFiles"
          :multiple="false"
          :show-file-list="false"
          :data="token"
          :before-upload="beforeUploadFile"
          :on-success="handleUploadSuccess">
          <el-button size="small" type="primary">选取文件</el-button>
          <span>（每次导入前，请先下载最新模板）</span>
        </el-upload>
        <el-button @click="downloadTemplate" type="text" class="font-blue">下载导入模板</el-button>
      </el-form-item>
    </el-form>
    <!-- 导入结果 -->
    <div class="mar-b-10" v-if="resultForm.total > 0">
      <div class="font-w">导入结果：</div>
      <div style="text-indent: 30px;">
        <span>共计数据<span class="font-red"> {{ resultForm.total }} </span>条</span>
        <span>，有效数据<span class="font-red"> {{ resultForm.validTotal }} </span>条</span>
        <span>，成功数据<span class="font-red"> {{ resultForm.successTotal }} </span>条</span>
        <span>，失败数据<span class="font-red"> {{ resultForm.failList.length }} </span>条</span>
        <span>，重复数据<span class="font-red"> {{ resultForm.repeatList.length }} </span>条</span>
      </div>
    </div>
    <!-- 导入失败列表 -->
    <div v-if="dataList.length > 0">
      <el-table class="mar-b-20" border :data="pageDataList">
        <template v-for="(headName, index) in resultForm.failHeadList">
          <el-table-column :label="headName[0]" 
            :key="index" 
            :min-width="resultForm.failHeadList.length - 1 == index ? '200px' : '120px'">

            <template slot-scope="scope">
              {{ scope.row[index] }}
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="currentPage"
                       :page-sizes="[10, 20, 50, 100]" :page-size="size"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="dataList.length">
        </el-pagination>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doImport">确定</el-button>
      <el-button @click="doCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import { excelCustomFormTemplate, importCustomForm } from '@/api/custom/customForm'

  export default {
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      },
      // 功能模块编码
      moduleCode: {
        type: String
      }
    },
    data() {
      return {
        // 上传表单
        uploadForm: {
          fileUrl: '',
          fileName: ''
        },
        // 导入结果表单
        resultForm: {
          // 导入总数
          total: '',
          // 导入有效数
          validTotal: '',
          // 导入成功数
          successTotal: '',
          // 导入重复列表
          repeatList: [],
          // 导入失败列表
          failList: [],
          // 导入失败列表头
          failHeadList: []
        },
        currentPage: 1,
        size: 10,
        // 总数据
        dataList: [],
        // 分页后数据
        pageDataList: [],
        token: '',
        loading: false
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.resetUpload()
          this.resetTable()
        }
      }
    },
    created() {
      this.resetUpload()
      this.resetTable()
      this.token = { accessToken: getToken() }
    },
    methods: {
      // 重置上传
      resetUpload() {
        this.uploadForm = {
          fileUrl: '',
          fileName: ''
        }
      },
      // 重置列表
      resetTable() {
        this.resultForm = {
          total: '',
          validTotal: '',
          successTotal: '',
          repeatList: [],
          failList: [],
          failHeadList: []
        }
        this.size = 10
        this.currentPage = 1
        this.dataList = []
        this.pageDataList = []
      },
      // 上传前校验事件
      beforeUploadFile(file) {
        const ext = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (ext !== 'xlsx') {
          this.$message.error('请上传xlsx格式的Excel')
          return false
        } else {
          this.loading = true
        }
        return true
      },
      // 上传成功后事件
      handleUploadSuccess(res, file) {
        this.loading = false
        if (res.code !== 101) {
          this.$message.error(res.msg)
          return
        }
        this.uploadForm = {
          fileUrl: res.data[0],
          fileName: file.name
        }
        this.resetTable()
        this.$message({ type: 'success', message: '文件已上传' })
      },
      // 导出自定义表单模板
      downloadTemplate() {
        if (!this.moduleCode) {
          this.$message({ type: 'error', message: '功能模块编码不能为空' })
          return
        }
        window.open(excelCustomFormTemplate(this.moduleCode, this.getEnterpriseId()), '_blank')
      },
      // 确定事件
      doImport() {
        if (!this.uploadForm.fileUrl) {
          this.$message.error('请上传导入文件')
          return
        }
        this.loading = true
        this.resetTable()
        importCustomForm(this.moduleCode, this.getEnterpriseId(), this.uploadForm.fileUrl).then(response => {
          this.loading = false
          if (response.isError) return
          Object.assign(this.resultForm, response.data)
          this.dataList = this.resultForm.failList.concat(this.resultForm.repeatList)
          this.calPageData()
        })
      },
      // 取消事件
      doCancel() {
        this.$emit('close')
      },
      // 计算获取分页数据
      calPageData() {
        const start = (this.currentPage - 1) * this.size
        const end = this.currentPage * this.size
        this.pageDataList = this.dataList.slice(start, end)
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.currentPage = val
        this.calPageData()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.currentPage = 1
        this.size = val
        this.calPageData()
      }
    }
  }
</script>
